<template>
	<view :style="skin" class="content setting">
		<view class="layout">
			<u-cell-group :border="false">
				<u-cell :isLink="true" arrow-direction="right" :border="false" size="large"
					@click="handleSkip('/pagesUserInfo/userInfo/userInfo')">
					<text slot="title" class="title">{{$t('me.PersonalInformation')}}</text>
					<!-- <text slot="title" class="title">{{$t('lease.title')}}</text> -->
				</u-cell>
				<u-cell :isLink="true" arrow-direction="right" :border="false" size="large">
					<text slot="title" class="title" @click="handleSkip('/pagesUserInfo/about/about')">{{$t('me.AboutUs')}}</text>
				</u-cell>
				<u-cell :isLink="true" arrow-direction="right" :border="false" size="large">
					<text slot="title" class="title" @click="intoWebView('privacy')">{{$t('me.PrivacyPolicy')}}</text>
				</u-cell>
				<u-cell :isLink="true" arrow-direction="right" :border="false" size="large">
					<text slot="title" class="title" @click="intoWebView('protocol')">{{$t('me.TermsService')}}</text>
				</u-cell>
			</u-cell-group>
		</view>

		<view class="layout">
			<u-cell-group :border="false">
				<u-cell :isLink="true" arrow-direction="right" :border="false" size="large" @click="langShow = true">
					<text slot="title" class="title">{{$t('me.language')}}</text>
					<text slot="value" class="title">{{$i18n.locale == 'en'?'English':'中文'}}</text>
				</u-cell>

				<!-- <u-cell :isLink="true" arrow-direction="right" :border="false" size="large"
					@click="handleSkip('/pagesUserInfo/accountCancel/accountCancel')">
					<text slot="title" class="title">{{$t('me.AccountDeactivation')}}</text>
				</u-cell> -->
			</u-cell-group>
		</view>



		<view class="bottom">
			<u-button color="var(--subjectColor)" @click="showConfirm = true">{{$t('me.logOut')}}
			</u-button>
		</view>

		<DialogPopup @btnCancel="showConfirm=false" @btnConfirm="confirmLogout" :show="showConfirm" :title="$t('me.Prompt')"
			handleType="text" :textInfo="$t('me.Confirmlog')"></DialogPopup>


		<u-action-sheet :closeOnClickOverlay="true" @close="langShow = false" :cancelText="$t('me.Prompt')"
			:actions="langList" @select="langSelect" :show="langShow"></u-action-sheet>

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		logout
	} from '@/api/login.js'
	import DialogPopup from '@/components/DialogPopup.vue'
	import {
		getOffMoney
	} from '@/utils/sql/sqloffLineDtoList.js'
	import {
		getTrunOver
	} from '@/utils/sql/sqlTrunoverDtoList.js'
	import {
		getInCome
	} from '@/utils/sql/sqlInComeDtoList.js'
	import {
		getNoSyncLease,
		getLease
	} from '@/utils/sql/sqllease.js'
	import {
		encryption,
		setSyncDevice
	} from '@/utils/index.js'
	import {
		leaSyn,
	} from '@/api/leaData.js'
	import {
		delDBUser,
		delDBdeviceInfo,
		delDBdeviceType,
		delDBlease,
		delDBmoney,
		delDBprice,
		delDBpassConfig
	} from '@/utils/sql/sqlUser.js'
	import {
		getPassConfig,
	} from '@/utils/sql/sqlPassConfig.js'
	export default {
		data() {
			return {
				showConfirm: false,
				showClose: false,
				langShow: false,
				langList: [{
						name: '中文',
						index: 0,
					},
					{
						name: 'English',
						index: 1,
					},
				],
			};
		},
		computed: {
			...mapState({
				skin: state => state.theme.skin
			}),
			i18n() {
				return this.$t()
			}

		},
		onLoad() {
			console.log(this.$i18n.locale);
		},
		methods: {
			...mapMutations(['removeSelect']),
			langSelect(item) {
				if (item.index == 1) {
					this.$i18n.locale = "en"
					uni.setStorageSync('lang', 'en')
				} else {
					this.$i18n.locale = "zh"
					uni.setStorageSync('lang', 'zh')
				}

			},
			// async syncLease() {
			// 	let res = await getLease();

			// 	let newArr = res.data.filter(item => {
			// 		return !(item.leaseStatus == 1 && item.iSync == 1) && item.iSync != 'null'
			// 	})
			// 	console.log('============', newArr);
			// 	let syncData = {
			// 		"data": newArr,
			// 		"synOpe": "local"
			// 	}
			// 	console.log(syncData);
			// 	leaSyn({
			// 		edata: encryption(JSON.stringify(syncData))
			// 	}).then(leRes => {
			// 		console.log(leRes);
			// 	})


			// },
			async delDB() {
				let res11 = await delDBUser()
				let res22 = await delDBdeviceInfo()
				let res33 = await delDBdeviceType()
				let res44 = await delDBlease()
				let res55 = await delDBmoney()
				let res66 = await delDBprice()
				let res77 = await delDBpassConfig()
			},
			async confirmLogout() {



				let res1 = await getOffMoney();
				let res2 = await getTrunOver();
				let res3 = await getInCome();
				let res4 = await getNoSyncLease();
				let res1Len = res1.data.length;
				let res2Len = res2.data.length;
				let res3Len = res3.data.length;
				let res4Len = res4.data.length;
				if (res1Len == 0 && res2Len == 0 && res3Len == 0 && res4Len == 0) {
					this.handleLogout();
				} else {
					// this.showConfirm = false
					// uni.showToast({
					// 	title: 'Please select Synchronize data',
					// 	icon: 'none'
					// })
					this.syncMoney()
				}

			},
			async syncMoney() { //同步金钱
				uni.showLoading({
					title: this.$t('me.SyncingData'),
					icon: 'loading',
				})
				let offRes = await getOffMoney();
				let inRes = await getInCome();
				let overRes = await getTrunOver();
				let syncData = {
					data: {
						amountIncome: null,
						amountOffline: null,
						amountTurnover: null,
						synAmountIncomeDtoList: null,
						synAmountOfflineDtoList: null,
						synAmountTurnoverDtoList: null,
					},
					synOpe: 'amount'
				}

				if (offRes.data.length > 0) {
					let offResLen = offRes.data.length - 1;
					syncData.data.amountOffline = offRes.data[offResLen].offlineAmountAll;
					syncData.data.synAmountOfflineDtoList = offRes.data
				}

				if (inRes.data.length > 0) {
					let inResLen = inRes.data.length - 1;
					syncData.data.amountIncome = inRes.data[inResLen].incomeAmountAll;
					syncData.data.synAmountIncomeDtoList = inRes.data
				}

				if (overRes.data.length > 0) {
					let overResLen = overRes.data.length - 1;
					syncData.data.amountTurnover = overRes.data[overResLen].turnoverAmountAll;
					syncData.data.synAmountTurnoverDtoList = overRes.data
				}


				let res = await leaSyn({
					edata: encryption(JSON.stringify(syncData))
				})
				if (res.code == 0) {

					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: this.$t('me.SyncDatasucc'),
							icon: 'success'
						})

						setTimeout(() => {
							this.syncDevice()
						}, 1000)
					}, 1000)


				} else {
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: res.msg,
							icon: 'error'
						})
					}, 1000)

				}
			},
			syncPass() {
				getPassConfig().then(res => {
					let syncData = {
						"synOpe": "sec",
						data: res.data
					}
					leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}).then(res => {
						console.log(res);
					})

				})
			},
			async syncDevice() {
				// 获取所有未同步的数据
				let leaRes = await getNoSyncLease();

				let syncArr = setSyncDevice(leaRes.data)

				if (syncArr.length == 0) {
					uni.showToast({
						title: this.$t('me.Nodevicesync'),
						icon: 'none'
					})
					this.handleLogout();
					return false
				}
				uni.showLoading({
					title: this.$t('me.SyncingDevice'),
					icon: 'loading',
				})
				let promiseAll = []
				syncArr.forEach(async item => {
					let syncData = {
						data: item,
						"synOpe": "lease"
					}

					promiseAll.push(leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}))
				})
				console.log(promiseAll);
				Promise.all(promiseAll).then(results => {
					let result = results.every(ele => ele.code == 0);
					if (result) {

						uni.hideLoading();
						uni.showToast({
							title: this.$t('me.SyncDevicesucc'),
							icon: 'success'
						})
						this.handleLogout();


					} else {
						let err = results.find(e => {
							return e.code != 0
						})
						setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: err.msg,
								icon: 'error'
							})
						})
					}
				}).catch(error => {
					console.log(error, '错误')
				})



			},
			handleLogout() {
				getPassConfig().then(passRes => {
					let syncData = {
						"synOpe": "sec",
						data: passRes.data
					}
					leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}).then(leaRes => {
						console.log(leaRes);
						
						logout().then(outRes => {
							console.log(outRes);
							if (outRes.code == 0) {
								this.delDB()
						
								setTimeout(() => {
									let lang = uni.getStorageSync('lang')
									uni.clearStorageSync();
						
									uni.setStorageSync('lang', lang);
									this.removeSelect();
						
									uni.reLaunch({
										url: '/pages/login/login'
									})
								}, 1000)
						
							} else {
								uni.showToast({
									title: outRes.msg,
									icon: 'none'
								})
							}
						
						})
					})
				
				})

			},
			handleSkip(url) {

				uni.navigateTo({
					url: url
				})
			},
			intoWebView(type) {
				uni.navigateTo({
					url: `/pages/webview/webview?type=${type}`
				})
			}
		},
		components: {
			DialogPopup
		}
	}
</script>

<style lang="scss" scoped>
	.setting {
		padding-top: 32px;
		box-sizing: border-box;

		.layout {
			width: calc(100% - 35px);
			margin: 0 auto 19px;
			background-color: white;
			border-radius: 19px;
			padding-bottom: 16px;
			background-color: #fff;

			.title {
				color: var(--subjectTextColor);
				font-size: 17px;
				font-weight: 400;
			}

		}

		.bottom {
			width: calc(100% - 32px);
			margin: 0 auto;
			height: 48px;
			display: flex;
			align-items: center;
			justify-content: space-evenly;
		}
	}
</style>